<template>
  <view>
    <view class="content">
      <view class="row">
        <view class="nominal"> 收件人 </view>
        <view class="input">
          <input placeholder="请输入收件人姓名" type="text" v-model="name" />
        </view>
      </view>
      <view class="row">
        <view class="nominal"> 电话号码 </view>
        <view class="input">
          <input placeholder="请输入收件人电话号码" type="text" v-model="tel" />
        </view>
      </view>
      <view class="row">
        <view class="nominal"> 所在地区 </view>
        <view class="input" @tap="chooseCity">
          {{ region.label }}
        </view>
      </view>
      <view class="row">
        <view class="nominal"> 详细地址 </view>
        <view class="input">
          <textarea
            v-model="detailed"
            auto-height="true"
            placeholder="输入详细地址"
          ></textarea>
        </view>
      </view>
      <view class="row">
        <view class="nominal"> 设置默认地址 </view>
        <view class="input switch">
          <switch
            color="#f06c7a"
            :checked="isDefault"
            @change="isDefaultChange"
            :disabled="editType === 'add' && isForcedDefault"
          />
          <text v-if="editType === 'add' && isForcedDefault" class="default-tip"
            >当前地址自动设为默认</text
          >
        </view>
      </view>
      <view class="row" v-if="editType == 'edit'" @tap="del">
        <view class="del"> 删除收货地址 </view>
      </view>
    </view>
    <view class="save" @tap="save">
      <view class="btn">
        {{ editType == "edit" ? "保存地址" : "新增地址" }}
      </view>
    </view>
    <mpvue-city-picker
      :themeColor="themeColor"
      ref="mpvueCityPicker"
      :pickerValueDefault="cityPickerValue"
      @onCancel="onCancel"
      @onConfirm="onConfirm"
    ></mpvue-city-picker>
  </view>
</template>

<script>
import mpvueCityPicker from "@/components/mpvue-citypicker/mpvueCityPicker.vue";
import {
  createAddress,
  updateAddress,
  deleteAddress,
  getAddressById,
  setDefaultAddress,
} from "@/common/api/address.js";
import { validateAddress } from "@/common/utils/address.js";

export default {
  components: {
    mpvueCityPicker,
  },
  data() {
    return {
      editType: "add", // 默认为新增模式
      id: "",
      name: "",
      tel: "",
      detailed: "",
      isDefault: false,
      isForcedDefault: false, // 是否是强制设置的默认地址
      cityPickerValue: [0, 0, 1],
      themeColor: "#007AFF",
      region: { label: "请点击选择地址", value: [], cityCode: "" },
      customerId: "", // 客户ID
      itemData: {},
    };
  },
  onLoad(options) {
    this.customerId = uni.getStorageSync("userInfo").id || "";
    this.editType = options.type;
    if (this.editType === "edit" && options.itemData) {
      this.itemData = JSON.parse(options.itemData);

      this.id = this.itemData.id;
      this.name = this.itemData.name;
      this.tel = this.itemData.phone;
      this.detailed = this.itemData.address;
      this.isDefault = this.itemData.isDefault;
      const { cityPickerValue } = JSON.parse(
        this.itemData.extraInfo || "{}"
      ) || { cityPickerValue: [0, 0, 1] };
      this.region = {
        label: this.itemData.region,
        value: cityPickerValue,
        cityCode: "",
      };
      this.cityPickerValue = cityPickerValue;
    } else if (this.editType === "add") {
      // 新增地址时，检查是否有默认地址
      this.checkDefaultAddress();
    }
  },
  methods: {
    // 检查是否有默认地址
    async checkDefaultAddress() {
      try {
        // 获取地址列表
        const { getAddressList } = await import("@/common/api/address.js");
        const res = await getAddressList(this.customerId);

        if (res && res.data && res.data.ok) {
          const addressList = res.data.data || [];
          // 检查是否有默认地址
          const hasDefaultAddress = addressList.some(
            (address) => address.isDefault
          );

          if (!hasDefaultAddress) {
            // 如果地址表里没有默认地址，强制设为默认地址
            this.isDefault = true;
            this.isForcedDefault = true;
          } else {
            // 如果地址表里已有默认地址，不强制设置
            this.isDefault = false;
            this.isForcedDefault = false;
          }
        } else {
          // 如果获取地址列表失败，为了安全起见，设为默认地址
          this.isDefault = true;
        }
      } catch (error) {
        // 如果检查失败，为了安全起见，也设为默认地址
        this.isDefault = true;
      }
    },

    onCancel(e) {},

    chooseCity() {
      this.$refs.mpvueCityPicker.show();
    },

    onConfirm(e) {
      this.region = e;
      this.cityPickerValue = e.value;
    },

    isDefaultChange(e) {
      // 如果是新增模式且是强制设置的默认地址，不允许取消
      if (this.editType === "add" && this.isForcedDefault && !e.detail.value) {
        uni.showToast({
          title: "首个地址必须设为默认",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      this.isDefault = e.detail.value;
    },

    del() {
      if (this.isDefault) {
        uni.showToast({
          title: "默认地址不能删除",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      uni.showModal({
        title: "删除提示",
        content: "你将删除这个收货地址",
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: "删除中...",
            });

            deleteAddress(this.id)
              .then((res) => {
                uni.hideLoading();
                // 删除成功，API返回的数据结构可能包含ok字段或直接返回成功状态
                if (res && res.data.ok) {
                  // 发送事件通知地址列表页面刷新
                  uni.$emit("refreshAddressList");

                  uni.showToast({
                    title: "删除成功",
                    icon: "success",
                    duration: 1500,
                    success() {
                      // 延迟返回，确保Toast显示完成
                      setTimeout(() => {
                        uni.navigateBack();
                      }, 1500);
                    },
                  });
                } else {
                  uni.showToast({
                    title: "删除失败",
                    icon: "none",
                  });
                }
              })
              .catch((err) => {
                uni.hideLoading();
                uni.showToast({
                  title: "删除失败",
                  icon: "none",
                });
              });
          } else if (res.cancel) {
          }
        },
      });
    },
    async save() {
      // 验证表单
      const validationData = {
        name: this.name,
        phone: this.tel,
        address: this.region.label + " " + this.detailed,
      };

      const validation = validateAddress(validationData);
      if (!validation.valid) {
        uni.showToast({ title: validation.message, icon: "none" });
        return;
      }

      if (this.region.value.length == 0) {
        uni.showToast({ title: "请选择收件地址", icon: "none" });
        return;
      }

      // 构建地址数据
      const addressData = {
        name: this.name,
        phone: this.tel,
        region: this.region.label,
        address: this.detailed,
        customerId: this.customerId,
        isDefault: this.isDefault,
        extraInfo: JSON.stringify({ cityPickerValue: this.cityPickerValue }),
      };

      uni.showLoading({
        title: "正在提交",
      });

      if (this.editType == "edit") {
        // 更新地址
        updateAddress(this.id, addressData)
          .then((res) => {
            uni.hideLoading();
            if (res && (res.ok || res.success || res.status === "success")) {
              // 发送事件通知地址列表页面刷新
              uni.$emit("refreshAddressList");

              uni.showToast({
                title: "更新成功",
                icon: "success",
                duration: 1500,
                success() {
                  setTimeout(() => {
                    uni.navigateBack();
                  }, 1500);
                },
              });
            } else {
              uni.showToast({
                title: "更新失败",
                icon: "none",
              });
            }
          })
          .catch((err) => {
            uni.hideLoading();
            uni.showToast({
              title: "更新失败",
              icon: "none",
            });
          });
      } else {
        // 创建新地址
        createAddress(addressData)
          .then((res) => {
            uni.hideLoading();
            if (res && (res.ok || res.success || res.status === "success")) {
              // 发送事件通知地址列表页面刷新
              uni.$emit("refreshAddressList");

              uni.showToast({
                title: "创建成功",
                icon: "success",
                duration: 1500,
                success() {
                  setTimeout(() => {
                    uni.navigateBack();
                  }, 1500);
                },
              });
            } else {
              uni.showToast({
                title: "创建失败",
                icon: "none",
              });
            }
          })
          .catch((err) => {
            uni.hideLoading();
            uni.showToast({
              title: "创建失败",
              icon: "none",
            });
          });
      }
    },
  },
  // Vue标准生命周期：组件销毁前调用
  beforeDestroy() {
    // 清理城市选择器
    if (this.$refs.mpvueCityPicker && this.$refs.mpvueCityPicker.showPicker) {
      this.$refs.mpvueCityPicker.pickerCancel();
    }
  },
};
</script>
<style lang="scss">
.save {
  view {
    display: flex;
  }

  position: fixed;
  bottom: 0;
  width: 100%;
  height: 120upx;
  display: flex;
  justify-content: center;
  align-items: center;

  .btn {
    box-shadow: 0upx 5upx 10upx rgba(0, 0, 0, 0.4);
    width: 70%;
    height: 80upx;
    border-radius: 80upx;
    background-color: #f06c7a;
    color: #fff;
    justify-content: center;
    align-items: center;

    .icon {
      height: 80upx;
      color: #fff;
      font-size: 30upx;
      justify-content: center;
      align-items: center;
    }

    font-size: 30upx;
  }
}

.content {
  display: flex;
  flex-wrap: wrap;

  view {
    display: flex;
  }

  .row {
    width: 94%;

    margin: 0 3%;
    border-top: solid 1upx #eee;

    .nominal {
      width: 30%;
      height: 120upx;
      font-weight: 200;
      font-size: 30upx;
      align-items: center;
    }

    .input {
      width: 70%;
      padding: 20upx 0;
      align-items: center;
      font-size: 30upx;

      &.switch {
        justify-content: flex-end;
        flex-direction: column;
        align-items: flex-end;

        .default-tip {
          font-size: 22upx;
          color: #999;
          margin-top: 10upx;
        }
      }

      .textarea {
        margin: 20upx 0;
        min-height: 120upx;
      }
    }

    .del {
      width: 100%;
      height: 100upx;
      justify-content: center;
      align-items: center;
      font-size: 36upx;
      color: #f06c7a;
      background-color: rgba(255, 0, 0, 0.05);
      border-bottom: solid 1upx #eee;
    }
  }
}
</style>
